package com.jstyle.jclife.activity;

import android.Manifest;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.google.android.gms.fitness.data.DataType;
import com.jstyle.blesdk.cmdenum.SendCmdState;
import com.jstyle.blesdk.constant.DeviceKey;
import com.jstyle.blesdk.model.ExerciseMode;
import com.jstyle.blesdk.model.StepModel;
import com.jstyle.jclife.R;
import com.jstyle.jclife.utils.PermissionsUtil;
import com.jstyle.jclife.utils.ScreenUtils;

import java.util.Locale;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * 开始锻炼前的倒计时
 */
public class CountDownActivity extends BaseActivity implements AMapLocationListener {

    @BindView(R.id.iv_count_time)
    ImageView ivCountTime;
    @BindView(R.id.iv_count_start)
    ImageView ivCountStart;
    private Disposable observable;
    private static final String TAG = "CountDownActivity";
    private int position;

    private AMapLocationClient aMapLocationClient;
    private boolean isMainLand;
    boolean LocationChanged = false;
    private int GPS_REQUEST_CODE=400;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_countdown);
        ButterKnife.bind(this);
        position = getIntent().getIntExtra(TrackActivity.key_ExerciseMode, 0);
        initLocation();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(observable!=null&&!observable.isDisposed())observable.dispose();;
    }
    private void startCountDown(){

       Observable.intervalRange(0, 4, 0, 1, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<Long>() {
            @Override
            public void onSubscribe(Disposable d) {
                observable=d;
            }

            @Override
            public void onNext(Long value) {
                int count = (int) (3 - value);
                int id = getResources().getIdentifier("timer_" + count, "drawable", getPackageName());
                ivCountTime.setImageResource(id);
                ivCountTime.setScaleX(0);
                ivCountTime.setScaleY(0);
                ObjectAnimator oa1 = ObjectAnimator.ofFloat(ivCountTime, "scaleX", 0, 1);
                oa1.setDuration(800);
                ObjectAnimator oa2 = ObjectAnimator.ofFloat(ivCountTime, "scaleY", 0, 1);
                oa2.setDuration(800);
                AnimatorSet set = new AnimatorSet();
                set.playTogether(oa1, oa2);
                set.start();

            }

            @Override
            public void onError(Throwable e) {
                Log.i(TAG, "onError: " + e.getMessage());
            }

            @Override
            public void onComplete() {
                if(position==10){
                    startActivity(WorkOutActivity.class);
                }else  if(position==7){
                    startActivity(DanceActivity.class);
                }else if (position == 5) {
                    startActivity(YogaActivity.class);
                }else{
                    if(LocationChanged){
                        startActivity(isMainLand?TrackActivity.class:TrackGoogleActivity.class, TrackActivity.key_ExerciseMode, position);
                    }else{
                        Locale locale = getResources().getConfiguration().locale;
                        String country = locale.getCountry();
                        startActivity(country.toLowerCase().equals("cn")?TrackActivity.class:TrackGoogleActivity.class, TrackActivity.key_ExerciseMode, position);

                    }
                }
                finish();
            }
        });
        StepModel stepModel = new StepModel();
        stepModel.setStepState(false);
        sendData(SendCmdState.SET_STEP_MODEL, stepModel);
    }

    private void showEnableGps() {
        new AlertDialog.Builder(this,R.style.appalertdialog).setTitle(R.string.open_gps_setting_title)
                .setMessage(R.string.open_gps_setting_content)
                //  取消选项
                .setNegativeButton(getString(R.string.access_no),null)
                //  确认选项
                .setPositiveButton(getString(R.string.access_now), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        //跳转到手机原生设置页面
                        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        startActivityForResult(intent,GPS_REQUEST_CODE);
                    }
                })
                .setCancelable(false)
                .show();
    }

    @OnClick(R.id.iv_count_start)
    public void onViewClicked() {
       requestPermissions();
    }
    boolean startExercise;
    @Override
    public void dataCallback(Map<String, String> maps, SendCmdState sendCmdState) {
        super.dataCallback(maps, sendCmdState);
        switch (sendCmdState) {
            case Set_EXERCISE_MODE:
                String enable=maps.get(DeviceKey.KEnable_exercise);
                int enableValue=Integer.valueOf(enable);
                if(enableValue==1&&startExercise){
                    startExercise=false;
                    ivCountStart.setVisibility(View.GONE);
                    startCountDown();
                }else{
                    ScreenUtils.showSetSuccessFul(ivCountStart,getString(R.string.exit_exercise_mode));
                }
                break;
        }
    }

    private void initLocation(){
        aMapLocationClient=new AMapLocationClient(this);
        aMapLocationClient.setLocationListener(this);
        AMapLocationClientOption aMapLocationClientOption=new AMapLocationClientOption();
        aMapLocationClientOption.setOnceLocation(true);
        aMapLocationClientOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        aMapLocationClient.setLocationOption(aMapLocationClientOption);
        aMapLocationClient.startLocation();
    }
    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        isMainLand ="中国".equals(aMapLocation.getCountry())&&!"1852".equals((aMapLocation.getCityCode()));
        Log.i(TAG, "onLocationChanged: "+aMapLocation.getCountry());
       LocationChanged= !TextUtils.isEmpty(aMapLocation.getCountry());
    }


    private void requestPermissions() {

        PermissionsUtil.requestPermissions(this, new PermissionsUtil.PermissionListener() {
            @Override
            public void granted(String name) {
                startMode();
            }

            @Override
            public void NeverAskAgain() {

            }

            @Override
            public void disallow(String name) {

            }
        }, Manifest.permission.ACCESS_FINE_LOCATION);



    }

    private void startMode(){
        if(!PermissionsUtil.isLocServiceEnable(this)){
            showEnableGps();
            return;
        }
        ExerciseMode exerciseMode = new ExerciseMode();
        exerciseMode.setEnableStatus(ExerciseMode.Status_START);
        exerciseMode.setExerciseMode(position);
        sendData(SendCmdState.Set_EXERCISE_MODE, exerciseMode);
        startExercise=true;
    }

}
